<template>
  <scroll-view class="swiper-tab" scroll-x>
    <view :style="menuStyle" v-for="(item,index) in navList" :key="index" class="swiper-tab-item" :data-current="index"
          @tap="switchNav">{{item.title}}
    </view>
    <view class="block" :style="bottomStyle"></view>
  </scroll-view>
</template>

<script>
  import wxp from 'minapp-api-promise'
  import {ObjStyle} from '../common/js/base'

  export default {
    name: 'slider-nav',
    data() {
      return {
        winWidth: null,
        winHeight: null,
        navWidth: null
      }
    },
    props: {
      navList: {
        type: Array
      },
      menuWidth: {
        type: Number
      },
      currentTab: {
        type: Number,
        default: 0
      },
      font: {
        type: Number,
        default: 14
      }
    },
    methods: {
      switchNav(e) {
        let {current} = e.target.dataset
        if (this.currentTab === current) return false
        else {
          this.$emit('update:currentTab', current)
        }
      },
      swiperChange(e) {
        let {current} = e.target
        this.currentTab = current
      }
    },
    computed: {
      bottomStyle() {
        let leftWidth = (this.winWidth - this.navList.length * this.navWidth) / 2
        let width = this.navWidth + 'px'
        let left = leftWidth + this.navWidth * this.currentTab + 'px'
        let style = {left, width}
        return ObjStyle(style)
      },
      menuStyle() {
        let style = {}
        style['font-size'] = this.font + 'px'
        style['width'] = this.navWidth + 'px'
        return ObjStyle(style)
      }
    },
    async onLoad() {
      let info = await wxp.getSystemInfo()
      this.winWidth = info.windowWidth
      this.winHeight = info.windowHeight
      if (!this.menuWidth) {
        this.navWidth = this.winWidth / this.navList.length
      } else {
        this.navWidth = this.menuWidth
      }
    }
  }
</script>

<style lang="scss" scoped>
  .swiper-tab {
    width: 100%;
    text-align: center;
    line-height: 42px;
    white-space: nowrap;
    position: relative;
    .swiper-tab-item {
      display: inline-block;
      font-size: 18px;
      height: 42px;
      transition: all $time;
    }
    .block {
      display: block;
      position: absolute;
      left: 0;
      height: 2px;
      background: $slider-color;
      bottom: 20px;
      transition: left $time;
      z-index: 99;
    }
  }
</style>
